package tree.clue;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-06-05 13:10
 * @ Description :
 */
public class ThreadTree
{
    private ThreadTreeNode root;
    private ThreadTreeNode preNode = null;


    public void setRoot(ThreadTreeNode root)
    {
        this.root = root;
    }

    public void threadedNodes()
    {
        this.threadedNodes(root);
    }
    //对二叉树进行中序线索化
    public void threadedNodes(ThreadTreeNode node)
    {
        if (node == null)
        {
            return;
        }
        //1. 先线索化左子树
        threadedNodes(node.getLeft());

        //2. 线索化当前节点
        //当前节点的左指针域设置交给当前节点处理
        if (node.getLeft() == null)
        {
            //让当前节点的左指针指向前驱节点
            node.setLeft(preNode);
            //修改当前节点的左指针类型为线索
            node.setLeftType(1);
        }
        //当前节点的右指针域设置交给后继节点处理
        if (preNode != null && preNode.getRight() == null)
        {
            //让前驱节点的右指针指向当前节点
            preNode.setRight(node);
            //修改前驱节点的右指针类型为线索
            preNode.setRightType(1);
        }

        //每次处理当前节点后,让当前节点作为下一个节点的前驱
        preNode = node;

        //3. 线索化右子树
        threadedNodes(node.getRight());
    }

    //遍历中序线索化二叉树
    public void preThreadList()
    {
        ThreadTreeNode node = root;//存储当前遍历的节点
        while (node != null)
        {
            while (node.getLeftType() == 0)
            {
                node = node.getLeft();
            }
            System.out.println(node);

            while (node.getRightType() == 1)
            {
                node = node.getRight();
                System.out.println(node);
            }
            node = node.getRight();
        }
    }

    //前序遍历
    public void preOrder()
    {
        if (this.root != null)
        {
            this.root.preOrder();
        }
        else
        {
            System.out.println("根节点为空");
        }
    }

    public void midOrder()
    {
        if (root != null)
        {
            root.midOrder();
        }
        else
        {
            System.out.println("根节点为空");
        }
    }

    public void postOrder()
    {
        if (root != null)
        {
            root.postOrder();
        }
        else
        {
            System.out.println("根节点为空");
        }
    }

    public ThreadTreeNode preOrderSearch(int findNo)
    {
        if (root != null)
        {
            return root.preOrderSearch(findNo);
        }
        else
        {
            return null;
        }
    }

    public ThreadTreeNode midOrderSearch(int findNo)
    {
        if (root != null)
        {
            return root.midOrderSearch(findNo);
        }
        else
        {
            return null;
        }
    }

    public ThreadTreeNode postOrderSearch(int findNo)
    {
        if (root != null)
        {
            return root.postOrderSearch(findNo);
        }
        else
        {
            return null;
        }
    }

}
